#include "SypEngine.h"

#ifdef CHECKMEM
#include "mmgr.h"
#endif
namespace Syp
{

	Sprite::Sprite(const String& filename, PShort matIndex, float width, float height): NIndexedMesh("Sprite:" + filename, STATIC)
	{
		mat = Material::loadFromFile(filename);
		this->setDefaultMaterial(filename);
		assert( matIndex < mat->subMaterials.size() && "matIndex for createSprite is invalid for the material.");

		TextureObj* to = mat->subMaterials[ matIndex ].getTexture();
		setVertexType( Syp::VT );// data consists of vertices, followed by uv coordinates
		setRenderingFormat(Syp::FORMAT_QUADS);// vertices are in a Quad format

		Syp::IndexBlock ib;// We define a IndexBlock
		ib.materialID = matIndex;//Use SubMaterial from the Material we use
		pushBackIndexBlock(ib);//Add drawcall to mesh
		this->numOfVertices = 4;//We will have a total of 4 vertices making up the quad.
		/*if(width == 0)
		{
			width = static_cast<float>(to->getWidth());
		}
		if(height == 0)
		{
			height = static_cast<float>(to->getHeight());
		}*/

		data.resize(20);

		//Vertex 1 - Bottom Left
		data[0] = 0.0f;//x
		data[1] = 0.0f;//y
		data[2] = 0.0f;//z
		data[3] = 0.0f;//u
		data[4] = 0.0f;//v

		//Vertex 2 - Bottom Right
		data[5] = width;
		data[6] = 0.0f;
		data[7] = 0.0f;
		data[8] = 1.0f;
		data[9] = 0.0f;
		//Vertex 3 - Top Right
		data[10] = width;
		data[11] = height;
		data[12] = 0.0f;
		data[13] = 1.0f;
		data[14] = 1.0f;
		//Vertex 4 - Top Left
		data[15] = 0.0f;
		data[16] = height;
		data[17] = 0.0f;
		data[18] = 0.0f;
		data[19] = 1.0f;

		updateMesh();// We must update the mesh to reflect the changes we have made

	}

	void Sprite::setDimensions(float width, float height)
	{
		//Vertex 1 - Bottom Left
		data[0] = 0.0f;//x
		data[1] = 0.0f;//y
		data[2] = 0.0f;//z
		data[3] = 0.0f;//u
		data[4] = 0.0f;//v

		//Vertex 2 - Bottom Right
		data[5] = width;
		data[6] = 0.0f;
		data[7] = 0.0f;
		data[8] = 1.0f;
		data[9] = 0.0f;
		//Vertex 3 - Top Right
		data[10] = width;
		data[11] = height;
		data[12] = 0.0f;
		data[13] = 1.0f;
		data[14] = 1.0f;
		//Vertex 4 - Top Left
		data[15] = 0.0f;
		data[16] = height;
		data[17] = 0.0f;
		data[18] = 0.0f;
		data[19] = 1.0f;

		updateMesh();// We must update the mesh to reflect the changes we have made

	}

	Sprite* Sprite::createSprite(const String& name, PShort matIndex,float width, float height)
	{
		return new Sprite(name, matIndex, width, height);
	}
	Sprite::~Sprite()
	{
	}

}
